"""
python fujian1_splineAndSmooth_gragh.py
"""

import os
import json
import pandas as pd
import matplotlib.pyplot as plt

# 定义原始数据和平滑后数据的路径（相对路径）
original_data_dir = os.path.normpath("./fujian/fujian1/cubic_spline/interpolation_output")
smooth_data_dir = os.path.normpath("./fujian/fujian1/spline_then_smooth")
output_plot_dir = os.path.normpath("./fujian/fujian1/spline_then_smooth/comparison_plots")

# 确保输出图像目录存在
os.makedirs(output_plot_dir, exist_ok=True)

# 遍历平滑数据文件，并作图
for filename in os.listdir(smooth_data_dir):
    if filename.endswith(".json"):
        category_number = -1
        print("插值以后的数据文件的文件名：", filename)
        
        try:
            category_number = filename.split("category")[1].split(".")[0]
        except IndexError:
            print(f"Error: Filename '{filename}' does not match expected format.")
            continue

        # 构建原始数据和平滑数据的路径，并标准化路径格式
        original_file_path = os.path.normpath(os.path.join(original_data_dir, f"interpolation_category{category_number}.json"))
        smooth_file_path = os.path.normpath(os.path.join(smooth_data_dir, filename))

        # 检查路径是否存在
        if not os.path.exists(original_file_path):
            print(f"Warning: 插值以后的数据文件 '{original_file_path}' not found.")
            continue

        # 读取 JSON 文件
        with open(original_file_path, 'r') as f:
            original_data = json.load(f)
        with open(smooth_file_path, 'r') as f:
            smooth_data = json.load(f)

        # 转换为 DataFrame
        original_df = pd.DataFrame(original_data)
        original_df['date'] = pd.to_datetime(original_df['date'])
        
        smooth_df = pd.DataFrame(smooth_data)
        smooth_df['date'] = pd.to_datetime(smooth_df['date'])

        # 绘制折线图
        plt.figure(figsize=(10, 6))
        plt.plot(original_df['date'], original_df['inventory'], label="Original Data", color="blue", marker="o")
        plt.plot(smooth_df['date'], smooth_df['inventory'], label="Smoothed Data", color="orange", marker="x")
        
        plt.xlabel("Date")
        plt.ylabel("Inventory")
        plt.title(f"Category {category_number} - Original vs Smoothed Data")
        plt.legend()
        
        # 保存图像
        plot_filename = f"comparison_category{category_number}.png"
        plt.savefig(os.path.join(output_plot_dir, plot_filename))
        plt.close()

print("所有类别的对比图已生成，保存到:", output_plot_dir)
